import express from 'express';
import { randomUUID } from 'crypto';
import cors from 'cors';

const app = express();
app.use(cors({
  origin: 'http://localhost:5173',
  methods: 'GET',
  allowedHeaders: 'Content-Type'
}));
const PORT = 3000;

// SSE路由
app.get('/sse', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5173');

  // 发送初始化事件
  res.write(`event:init\ndata:${JSON.stringify({ id: randomUUID() })}\n\n`);

  // 定时发送模拟数据
  const timer = setInterval(() => {
    res.write(`data:${JSON.stringify({
      timestamp: Date.now(),
      value: Math.random().toFixed(4)
    })}\n\n`);
  }, 2000);

  // 处理连接关闭
  req.on('close', () => {
    clearInterval(timer);
    console.log('Client disconnected');
  });
});

app.listen(PORT, () => {
  console.log(`SSE server running at http://localhost:${PORT}`);
});